package com.example.systemserver.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.example.systemserver.bean.ResultBean;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/upload")
    public ResultBean upload(@RequestParam("files") MultipartFile file) throws IOException {
        //file就是传递过来的文件
        // 获取图片的后缀名，生成唯一的名称
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = IdUtil.getSnowflakeNextIdStr() + suffix;
        file.transferTo(new File("C:\\Users\\Administrator\\Desktop\\images\\"+newFileName));

        String imagePath = "http://localhost:8080/file/getImage/"+newFileName;
        return new ResultBean(200,"上传成功",imagePath);
    }

    //http://localhost:8080/file/getImage?filename=1967545776862531584.png
    //http://localhost:8080/file/getImage/1967545776862531584.png
    @RequestMapping("/getImage/{filename}")
    public void getImage(@PathVariable String filename, HttpServletResponse response) throws Exception {
        log.info("/file/getImage,获取文件,请求参数:{}",filename);
        // 找到这个文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\images\\"+filename);
        InputStream in = new FileInputStream( file);
        // 获取到通向浏览器的输出流
        OutputStream out = response.getOutputStream();
        IoUtil.copy(in, out);
    }

}
